package com.haidechizi.mybatis.demo.service;


import com.haidechizi.mybatis.demo.dao.UserDao;
import com.haidechizi.mybatis.demo.entity.Log;
import com.haidechizi.mybatis.demo.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private LogService logService;


    public User get(Long id) {
        return userDao.get(new User(id));
    }

    @Transactional
    public User insertUser(User user) throws Exception {
        userDao.insertUser(user);
        if (user.getId() != null) {
            throw new Exception("测试异常回滚");
        }
        return user;
    }

    @Transactional
    public User updateUser(User user) {
        userDao.updateUser(user);
        try {
            Log log = buildLog();
            logService.insertLog2(log);
        } catch (Exception e) {
            log.error("保存日志失败", e);
        }
        return user;
    }

    public void deleteUser(User user) {
        userDao.deleteUser(user);
    }


    private Log buildLog() {
        Log log = new Log();
        log.setSystemName("user");
        log.setBusinessName("user");
        return log;
    }
}
